package com.qqtop10.manager.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtop10.manager.model.Broadcast;
import com.qqtop10.manager.model.PagingArgs;
import com.qqtop10.manager.model.Result;
import com.qqtop10.manager.service.BroadcastService;
import com.qqtop10.manager.service.BuildHtmlService;

/**
 * 
 * @ClassName: BroadcastController
 * @Description: 消息管理控制器
 * @author ChenXinwei
 * @date 2015/9/3
 *
 */
@RequestMapping("/manager/broadcast/")
@Controller
public class BroadcastController extends BaseController {
	@Autowired
	@Qualifier("broadcastService")
	private BroadcastService broadcastService;
	@Autowired
	private BuildHtmlService buildHtmlService;

	@RequestMapping("all.do")
	@ResponseBody
	public Result all(Broadcast input) {
		try {
			PagingArgs pagingArgs = getPagingArgs();
			if (pagingArgs.get_sorters() == null) {
				pagingArgs.set_sorters(new String[] { "createtime desc" });
			}
			return page(broadcastService.count(input),
					broadcastService.all(input, pagingArgs));
		} catch (Exception e) {
			return excep(e);
		}
	}

	@RequestMapping("put.do")
	@ResponseBody
	public Result put(Broadcast input) {
		try {
			if (input == null || input.getTitle() == null
					|| input.getContent() == null) {
				return err("有些必须的参数未指定。");
			}
			input.setUuid(newId());
			input.setCreator(getLogindUuid());
			input.setCreatetime(now());
			if (broadcastService.put(input)) {
				buildHtmlService.buildPage(null, "notice.html", "notice/"
						+ input.getUuid() + ".html", input);
				return ok("操作成功！");
			}
			return err("操作失败！");
		} catch (Exception e) {
			return excep(e);
		}
	}

	@RequestMapping("delete.do")
	@ResponseBody
	public Result delete(int[] ids) {
		try {
			int count = 0;
			for (int i = 0; i < ids.length; i++) {
				if (!broadcastService.delete(ids[i])) {
					ids[count] = ids[i];
					++count;
				}
			}
			if (count == 0) {
				return ok("操作成功！");
			} else if (count < ids.length) {
				return ok("操作已完成。但有些数据没有删除成功。");
			} else {
				return err("全部操作失败！");
			}
		} catch (Exception e) {
			return excep(e);
		}
	}
}
